﻿namespace NTLib.Core.ScopeLock
{
    using NTLib.Core.Memory;
    using System;

    /// <summary>
    /// Used to managed an action in construction and dispose methods
    /// </summary>
    public class ScopeLockItem<T> : Disposable
    {
        #region Fields

        private readonly Action<T> _disposeAction;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the object.
        /// </summary>
        public T Object { get; }

        #endregion

        #region Ctor

        /// <summary>
        /// Initializes a new instance of the <see cref="ScopeLockItem{T}"/> class.
        /// </summary>
        public ScopeLockItem(T obj, Action<T> disposeAction)
        {
            this._disposeAction = disposeAction;
            this.Object = obj;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (!base.IsDisposed && this._disposeAction != null)
                this._disposeAction(this.Object);

            base.Dispose(disposing);
        }

        #endregion
    }
}
